#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
备忘录模式 (Memento Pattern) - Python实现详解

备忘录模式是一种行为设计模式，它允许在不破坏封装性的前提下，
捕获一个对象的内部状态，并在该对象之外保存这个状态。
这样以后就可将该对象恢复到原先保存的状态。

与Java对比：
1. Python的pickle模块提供了更简单的序列化方案
2. Python的深拷贝机制更加灵活
3. Python支持更多的状态保存方式（字典、JSON等）
4. Python的动态特性使得状态管理更加灵活

作者: Assistant
日期: 2024
"""

import copy
import pickle
import json
import time
import threading
from abc import ABC, abstractmethod
from typing import Any, Dict, List, Optional, Union
from dataclasses import dataclass, asdict
from datetime import datetime
import weakref


# ============================================================================
# 1. 传统备忘录模式实现
# ============================================================================

class Memento:
    """
    备忘录类 - 存储发起人的内部状态
    
    在传统实现中，备忘录类通常是发起人的内部类，
    以确保只有发起人可以访问备忘录的内容。
    """
    
    def __init__(self, state: Any):
        self._state = state
        self._timestamp = datetime.now()
    
    def get_state(self) -> Any:
        """获取保存的状态"""
        return self._state
    
    def get_timestamp(self) -> datetime:
        """获取创建时间戳"""
        return self._timestamp
    
    def __str__(self) -> str:
        return f"Memento(state={self._state}, time={self._timestamp.strftime('%H:%M:%S')})"


class Originator:
    """
    发起人类 - 创建备忘录来保存当前状态，也可以使用备忘录来恢复状态
    """
    
    def __init__(self, initial_state: Any = None):
        self._state = initial_state
    
    def set_state(self, state: Any) -> None:
        """设置状态"""
        print(f"发起人: 设置状态为 {state}")
        self._state = state
    
    def get_state(self) -> Any:
        """获取当前状态"""
        return self._state
    
    def create_memento(self) -> Memento:
        """创建备忘录保存当前状态"""
        print(f"发起人: 创建备忘录，保存状态 {self._state}")
        return Memento(copy.deepcopy(self._state))
    
    def restore_from_memento(self, memento: Memento) -> None:
        """从备忘录恢复状态"""
        self._state = memento.get_state()
        print(f"发起人: 从备忘录恢复状态为 {self._state}")
    
    def __str__(self) -> str:
        return f"Originator(state={self._state})"


class Caretaker:
    """
    管理者类 - 负责保存备忘录，但不能对备忘录的内容进行操作或检查
    """
    
    def __init__(self):
        self._mementos: List[Memento] = []
        self._current_index = -1
    
    def save_memento(self, memento: Memento) -> None:
        """保存备忘录"""
        # 如果当前不在最新位置，删除后续的备忘录
        if self._current_index < len(self._mementos) - 1:
            self._mementos = self._mementos[:self._current_index + 1]
        
        self._mementos.append(memento)
        self._current_index += 1
        print(f"管理者: 保存备忘录 #{self._current_index}")
    
    def get_memento(self, index: int = -1) -> Optional[Memento]:
        """获取指定索引的备忘录"""
        if index == -1:
            index = self._current_index
        
        if 0 <= index < len(self._mementos):
            return self._mementos[index]
        return None
    
    def undo(self) -> Optional[Memento]:
        """撤销到上一个状态"""
        if self._current_index > 0:
            self._current_index -= 1
            memento = self._mementos[self._current_index]
            print(f"管理者: 撤销到备忘录 #{self._current_index}")
            return memento
        print("管理者: 无法撤销，已经是最早的状态")
        return None
    
    def redo(self) -> Optional[Memento]:
        """重做到下一个状态"""
        if self._current_index < len(self._mementos) - 1:
            self._current_index += 1
            memento = self._mementos[self._current_index]
            print(f"管理者: 重做到备忘录 #{self._current_index}")
            return memento
        print("管理者: 无法重做，已经是最新的状态")
        return None
    
    def get_history(self) -> List[str]:
        """获取历史记录"""
        history = []
        for i, memento in enumerate(self._mementos):
            marker = " <- 当前" if i == self._current_index else ""
            history.append(f"#{i}: {memento}{marker}")
        return history
    
    def clear_history(self) -> None:
        """清空历史记录"""
        self._mementos.clear()
        self._current_index = -1
        print("管理者: 清空所有历史记录")


# ============================================================================
# 2. 增强型备忘录模式（支持多种序列化方式）
# ============================================================================

class SerializableMemento:
    """
    可序列化的备忘录类
    支持多种序列化方式：pickle、json、自定义
    """
    
    def __init__(self, state: Any, serialization_method: str = 'pickle'):
        self._serialization_method = serialization_method
        self._timestamp = datetime.now()
        self._serialized_state = self._serialize_state(state)
        self._metadata = {
            'method': serialization_method,
            'timestamp': self._timestamp.isoformat(),
            'size': len(self._serialized_state) if isinstance(self._serialized_state, (str, bytes)) else 0
        }
    
    def _serialize_state(self, state: Any) -> Union[bytes, str, Dict]:
        """序列化状态"""
        if self._serialization_method == 'pickle':
            return pickle.dumps(state)
        elif self._serialization_method == 'json':
            return json.dumps(state, default=str, ensure_ascii=False)
        elif self._serialization_method == 'copy':
            return copy.deepcopy(state)
        else:
            raise ValueError(f"不支持的序列化方法: {self._serialization_method}")
    
    def get_state(self) -> Any:
        """反序列化并获取状态"""
        if self._serialization_method == 'pickle':
            return pickle.loads(self._serialized_state)
        elif self._serialization_method == 'json':
            return json.loads(self._serialized_state)
        elif self._serialization_method == 'copy':
            return copy.deepcopy(self._serialized_state)
        else:
            raise ValueError(f"不支持的序列化方法: {self._serialization_method}")
    
    def get_metadata(self) -> Dict:
        """获取元数据"""
        return self._metadata.copy()
    
    def get_size(self) -> int:
        """获取序列化后的大小"""
        return self._metadata['size']
    
    def __str__(self) -> str:
        return f"SerializableMemento({self._serialization_method}, {self._metadata['size']} bytes)"


class AdvancedOriginator:
    """
    增强型发起人类
    支持多种序列化方式和状态验证
    """
    
    def __init__(self, initial_state: Any = None):
        self._state = initial_state
        self._state_validator = None
        self._change_listeners = []
    
    def set_state_validator(self, validator: callable) -> None:
        """设置状态验证器"""
        self._state_validator = validator
    
    def add_change_listener(self, listener: callable) -> None:
        """添加状态变化监听器"""
        self._change_listeners.append(listener)
    
    def set_state(self, state: Any) -> None:
        """设置状态（带验证）"""
        if self._state_validator and not self._state_validator(state):
            raise ValueError(f"状态验证失败: {state}")
        
        old_state = self._state
        self._state = state
        
        # 通知监听器
        for listener in self._change_listeners:
            try:
                listener(old_state, state)
            except Exception as e:
                print(f"监听器执行失败: {e}")
        
        print(f"增强发起人: 设置状态为 {state}")
    
    def get_state(self) -> Any:
        """获取当前状态"""
        return self._state
    
    def create_memento(self, serialization_method: str = 'pickle') -> SerializableMemento:
        """创建可序列化备忘录"""
        print(f"增强发起人: 创建备忘录 ({serialization_method})，保存状态 {self._state}")
        return SerializableMemento(self._state, serialization_method)
    
    def restore_from_memento(self, memento: SerializableMemento) -> None:
        """从备忘录恢复状态"""
        restored_state = memento.get_state()
        self.set_state(restored_state)
        print(f"增强发起人: 从备忘录恢复状态为 {restored_state}")


# ============================================================================
# 3. 文档编辑器示例（实际应用）
# ============================================================================

@dataclass
class DocumentState:
    """文档状态数据类"""
    content: str = ""
    cursor_position: int = 0
    selection_start: int = 0
    selection_end: int = 0
    font_size: int = 12
    font_family: str = "Arial"
    is_bold: bool = False
    is_italic: bool = False
    
    def to_dict(self) -> Dict:
        """转换为字典"""
        return asdict(self)
    
    @classmethod
    def from_dict(cls, data: Dict) -> 'DocumentState':
        """从字典创建"""
        return cls(**data)


class DocumentEditor:
    """
    文档编辑器 - 备忘录模式的实际应用示例
    """
    
    def __init__(self):
        self._state = DocumentState()
        self._history: List[SerializableMemento] = []
        self._current_index = -1
        self._max_history = 50  # 最大历史记录数
        self._auto_save_enabled = True
        self._last_save_time = time.time()
    
    def _auto_save(self) -> None:
        """自动保存"""
        if self._auto_save_enabled:
            current_time = time.time()
            # 每2秒自动保存一次
            if current_time - self._last_save_time > 2:
                self.save_state("自动保存")
                self._last_save_time = current_time
    
    def save_state(self, description: str = "") -> None:
        """保存当前状态"""
        # 如果当前不在最新位置，删除后续的历史记录
        if self._current_index < len(self._history) - 1:
            self._history = self._history[:self._current_index + 1]
        
        # 创建备忘录
        memento = SerializableMemento(self._state, 'json')
        memento._description = description
        
        self._history.append(memento)
        self._current_index += 1
        
        # 限制历史记录数量
        if len(self._history) > self._max_history:
            self._history.pop(0)
            self._current_index -= 1
        
        print(f"文档编辑器: 保存状态 - {description}")
    
    def undo(self) -> bool:
        """撤销操作"""
        if self._current_index > 0:
            self._current_index -= 1
            memento = self._history[self._current_index]
            self._state = DocumentState.from_dict(memento.get_state().to_dict())
            print(f"文档编辑器: 撤销到 {getattr(memento, '_description', '未知状态')}")
            return True
        print("文档编辑器: 无法撤销")
        return False
    
    def redo(self) -> bool:
        """重做操作"""
        if self._current_index < len(self._history) - 1:
            self._current_index += 1
            memento = self._history[self._current_index]
            self._state = DocumentState.from_dict(memento.get_state().to_dict())
            print(f"文档编辑器: 重做到 {getattr(memento, '_description', '未知状态')}")
            return True
        print("文档编辑器: 无法重做")
        return False
    
    def insert_text(self, text: str) -> None:
        """插入文本"""
        self.save_state(f"插入文本: '{text}'")
        
        content = self._state.content
        pos = self._state.cursor_position
        
        new_content = content[:pos] + text + content[pos:]
        self._state.content = new_content
        self._state.cursor_position = pos + len(text)
        
        self._auto_save()
    
    def delete_text(self, length: int) -> None:
        """删除文本"""
        if length <= 0:
            return
        
        self.save_state(f"删除 {length} 个字符")
        
        content = self._state.content
        pos = self._state.cursor_position
        
        if pos >= length:
            new_content = content[:pos-length] + content[pos:]
            self._state.content = new_content
            self._state.cursor_position = pos - length
        
        self._auto_save()
    
    def set_cursor_position(self, position: int) -> None:
        """设置光标位置"""
        max_pos = len(self._state.content)
        self._state.cursor_position = max(0, min(position, max_pos))
    
    def set_font_size(self, size: int) -> None:
        """设置字体大小"""
        self.save_state(f"设置字体大小: {size}")
        self._state.font_size = size
    
    def set_font_style(self, bold: bool = None, italic: bool = None) -> None:
        """设置字体样式"""
        changes = []
        if bold is not None:
            changes.append(f"粗体: {bold}")
            self._state.is_bold = bold
        if italic is not None:
            changes.append(f"斜体: {italic}")
            self._state.is_italic = italic
        
        if changes:
            self.save_state(f"设置字体样式: {', '.join(changes)}")
    
    def get_content(self) -> str:
        """获取文档内容"""
        return self._state.content
    
    def get_state_info(self) -> Dict:
        """获取状态信息"""
        return {
            'content_length': len(self._state.content),
            'cursor_position': self._state.cursor_position,
            'font_size': self._state.font_size,
            'font_family': self._state.font_family,
            'is_bold': self._state.is_bold,
            'is_italic': self._state.is_italic,
            'history_count': len(self._history),
            'current_index': self._current_index
        }
    
    def get_history_summary(self) -> List[str]:
        """获取历史记录摘要"""
        summary = []
        for i, memento in enumerate(self._history):
            marker = " <- 当前" if i == self._current_index else ""
            description = getattr(memento, '_description', '未知操作')
            timestamp = memento.get_metadata()['timestamp']
            summary.append(f"#{i}: {description} ({timestamp[:19]}){marker}")
        return summary


# ============================================================================
# 4. 游戏状态管理器（多玩家支持）
# ============================================================================

@dataclass
class GameState:
    """游戏状态"""
    level: int = 1
    score: int = 0
    lives: int = 3
    player_position: tuple = (0, 0)
    inventory: List[str] = None
    achievements: List[str] = None
    
    def __post_init__(self):
        if self.inventory is None:
            self.inventory = []
        if self.achievements is None:
            self.achievements = []


class GameStateManager:
    """
    游戏状态管理器
    支持多个存档槽位和自动保存
    """
    
    def __init__(self, max_save_slots: int = 10):
        self._current_state = GameState()
        self._save_slots: Dict[int, SerializableMemento] = {}
        self._auto_saves: List[SerializableMemento] = []
        self._max_save_slots = max_save_slots
        self._max_auto_saves = 20
        self._lock = threading.Lock()
    
    def save_game(self, slot: int, description: str = "") -> bool:
        """保存游戏到指定槽位"""
        with self._lock:
            try:
                if not (0 <= slot < self._max_save_slots):
                    print(f"无效的存档槽位: {slot}")
                    return False
                
                memento = SerializableMemento(self._current_state, 'pickle')
                memento._description = description or f"存档槽位 {slot}"
                memento._slot = slot
                
                self._save_slots[slot] = memento
                print(f"游戏状态管理器: 保存到槽位 {slot} - {description}")
                return True
            except Exception as e:
                print(f"保存失败: {e}")
                return False
    
    def load_game(self, slot: int) -> bool:
        """从指定槽位加载游戏"""
        with self._lock:
            try:
                if slot not in self._save_slots:
                    print(f"槽位 {slot} 没有存档")
                    return False
                
                memento = self._save_slots[slot]
                self._current_state = memento.get_state()
                description = getattr(memento, '_description', f"槽位 {slot}")
                print(f"游戏状态管理器: 从槽位 {slot} 加载 - {description}")
                return True
            except Exception as e:
                print(f"加载失败: {e}")
                return False
    
    def auto_save(self) -> None:
        """自动保存"""
        with self._lock:
            try:
                memento = SerializableMemento(self._current_state, 'pickle')
                memento._description = f"自动保存 {datetime.now().strftime('%H:%M:%S')}"
                
                self._auto_saves.append(memento)
                
                # 限制自动保存数量
                if len(self._auto_saves) > self._max_auto_saves:
                    self._auto_saves.pop(0)
                
                print(f"游戏状态管理器: 自动保存完成")
            except Exception as e:
                print(f"自动保存失败: {e}")
    
    def get_save_slots_info(self) -> Dict[int, Dict]:
        """获取存档槽位信息"""
        info = {}
        for slot, memento in self._save_slots.items():
            metadata = memento.get_metadata()
            state = memento.get_state()
            info[slot] = {
                'description': getattr(memento, '_description', f"槽位 {slot}"),
                'timestamp': metadata['timestamp'],
                'level': state.level,
                'score': state.score,
                'lives': state.lives
            }
        return info
    
    def delete_save(self, slot: int) -> bool:
        """删除存档"""
        with self._lock:
            if slot in self._save_slots:
                del self._save_slots[slot]
                print(f"游戏状态管理器: 删除槽位 {slot} 的存档")
                return True
            return False
    
    # 游戏状态操作方法
    def set_level(self, level: int) -> None:
        """设置关卡"""
        self._current_state.level = level
        print(f"游戏: 进入第 {level} 关")
    
    def add_score(self, points: int) -> None:
        """增加分数"""
        self._current_state.score += points
        print(f"游戏: 获得 {points} 分，总分 {self._current_state.score}")
    
    def lose_life(self) -> bool:
        """失去生命"""
        if self._current_state.lives > 0:
            self._current_state.lives -= 1
            print(f"游戏: 失去一条生命，剩余 {self._current_state.lives} 条")
            return self._current_state.lives > 0
        return False
    
    def move_player(self, x: int, y: int) -> None:
        """移动玩家"""
        self._current_state.player_position = (x, y)
        print(f"游戏: 玩家移动到 ({x}, {y})")
    
    def add_item(self, item: str) -> None:
        """添加物品"""
        self._current_state.inventory.append(item)
        print(f"游戏: 获得物品 '{item}'")
    
    def unlock_achievement(self, achievement: str) -> None:
        """解锁成就"""
        if achievement not in self._current_state.achievements:
            self._current_state.achievements.append(achievement)
            print(f"游戏: 解锁成就 '{achievement}'")
    
    def get_current_state(self) -> GameState:
        """获取当前状态"""
        return copy.deepcopy(self._current_state)


# ============================================================================
# 5. 演示函数
# ============================================================================

def demonstrate_traditional_memento():
    """
    演示传统备忘录模式
    """
    print("\n=== 传统备忘录模式演示 ===")
    
    # 创建发起人和管理者
    originator = Originator("初始状态")
    caretaker = Caretaker()
    
    # 保存初始状态
    caretaker.save_memento(originator.create_memento())
    
    # 修改状态并保存
    originator.set_state("状态1")
    caretaker.save_memento(originator.create_memento())
    
    originator.set_state("状态2")
    caretaker.save_memento(originator.create_memento())
    
    originator.set_state("状态3")
    caretaker.save_memento(originator.create_memento())
    
    print(f"\n当前状态: {originator}")
    
    # 显示历史记录
    print("\n历史记录:")
    for record in caretaker.get_history():
        print(f"  {record}")
    
    # 撤销操作
    print("\n=== 撤销操作 ===")
    memento = caretaker.undo()
    if memento:
        originator.restore_from_memento(memento)
    
    memento = caretaker.undo()
    if memento:
        originator.restore_from_memento(memento)
    
    print(f"撤销后状态: {originator}")
    
    # 重做操作
    print("\n=== 重做操作 ===")
    memento = caretaker.redo()
    if memento:
        originator.restore_from_memento(memento)
    
    print(f"重做后状态: {originator}")


def demonstrate_advanced_memento():
    """
    演示增强型备忘录模式
    """
    print("\n=== 增强型备忘录模式演示 ===")
    
    # 创建增强型发起人
    originator = AdvancedOriginator({"name": "测试", "value": 100})
    
    # 设置状态验证器
    def validate_state(state):
        return isinstance(state, dict) and "value" in state and state["value"] >= 0
    
    originator.set_state_validator(validate_state)
    
    # 添加变化监听器
    def on_state_change(old_state, new_state):
        print(f"  监听器: 状态从 {old_state} 变为 {new_state}")
    
    originator.add_change_listener(on_state_change)
    
    # 测试不同的序列化方式
    print("\n=== 测试不同序列化方式 ===")
    
    # Pickle序列化
    pickle_memento = originator.create_memento('pickle')
    print(f"Pickle备忘录: {pickle_memento}, 大小: {pickle_memento.get_size()} bytes")
    
    # JSON序列化
    json_memento = originator.create_memento('json')
    print(f"JSON备忘录: {json_memento}, 大小: {json_memento.get_size()} bytes")
    
    # 深拷贝
    copy_memento = originator.create_memento('copy')
    print(f"Copy备忘录: {copy_memento}")
    
    # 修改状态
    originator.set_state({"name": "修改后", "value": 200, "extra": "新字段"})
    
    # 从不同备忘录恢复
    print("\n=== 从不同备忘录恢复 ===")
    originator.restore_from_memento(pickle_memento)
    originator.restore_from_memento(json_memento)
    
    # 测试状态验证
    print("\n=== 测试状态验证 ===")
    try:
        originator.set_state({"name": "无效", "value": -1})  # 应该失败
    except ValueError as e:
        print(f"验证失败（预期）: {e}")


def demonstrate_document_editor():
    """
    演示文档编辑器应用
    """
    print("\n=== 文档编辑器演示 ===")
    
    editor = DocumentEditor()
    
    # 编辑操作
    print("\n=== 编辑操作 ===")
    editor.insert_text("Hello")
    editor.insert_text(" World")
    editor.insert_text("!")
    
    print(f"当前内容: '{editor.get_content()}'")
    
    # 格式化操作
    editor.set_font_size(14)
    editor.set_font_style(bold=True)
    
    # 更多编辑
    editor.set_cursor_position(5)  # 移动到"World"前
    editor.insert_text(" Beautiful")
    
    print(f"修改后内容: '{editor.get_content()}'")
    
    # 显示状态信息
    print(f"\n状态信息: {editor.get_state_info()}")
    
    # 撤销操作
    print("\n=== 撤销操作 ===")
    editor.undo()  # 撤销插入"Beautiful"
    editor.undo()  # 撤销设置粗体
    editor.undo()  # 撤销设置字体大小
    
    print(f"撤销后内容: '{editor.get_content()}'")
    
    # 重做操作
    print("\n=== 重做操作 ===")
    editor.redo()  # 重做设置字体大小
    editor.redo()  # 重做设置粗体
    
    print(f"重做后内容: '{editor.get_content()}'")
    
    # 显示历史记录
    print("\n=== 历史记录 ===")
    for record in editor.get_history_summary():
        print(f"  {record}")


def demonstrate_game_state_manager():
    """
    演示游戏状态管理器
    """
    print("\n=== 游戏状态管理器演示 ===")
    
    game = GameStateManager()
    
    # 游戏进程
    print("\n=== 游戏进程 ===")
    game.add_score(100)
    game.move_player(10, 20)
    game.add_item("剑")
    game.add_item("盾牌")
    
    # 保存游戏
    game.save_game(0, "第一关开始")
    
    # 继续游戏
    game.set_level(2)
    game.add_score(200)
    game.move_player(30, 40)
    game.unlock_achievement("新手")
    
    # 保存到另一个槽位
    game.save_game(1, "第二关进行中")
    
    # 模拟死亡
    game.lose_life()
    game.lose_life()
    
    # 自动保存
    game.auto_save()
    
    # 显示当前状态
    current_state = game.get_current_state()
    print(f"\n当前游戏状态:")
    print(f"  关卡: {current_state.level}")
    print(f"  分数: {current_state.score}")
    print(f"  生命: {current_state.lives}")
    print(f"  位置: {current_state.player_position}")
    print(f"  物品: {current_state.inventory}")
    print(f"  成就: {current_state.achievements}")
    
    # 显示存档信息
    print("\n=== 存档信息 ===")
    save_info = game.get_save_slots_info()
    for slot, info in save_info.items():
        print(f"槽位 {slot}: {info['description']}")
        print(f"  时间: {info['timestamp'][:19]}")
        print(f"  关卡: {info['level']}, 分数: {info['score']}, 生命: {info['lives']}")
    
    # 加载之前的存档
    print("\n=== 加载存档 ===")
    game.load_game(0)
    
    loaded_state = game.get_current_state()
    print(f"加载后状态:")
    print(f"  关卡: {loaded_state.level}")
    print(f"  分数: {loaded_state.score}")
    print(f"  生命: {loaded_state.lives}")
    print(f"  位置: {loaded_state.player_position}")
    print(f"  物品: {loaded_state.inventory}")


def demonstrate_performance_comparison():
    """
    演示性能对比
    """
    print("\n=== 性能对比演示 ===")
    
    # 创建大型状态对象
    large_state = {
        'data': list(range(10000)),
        'matrix': [[i*j for j in range(100)] for i in range(100)],
        'text': "这是一个很长的文本" * 1000
    }
    
    print(f"\n测试数据大小: 约 {len(str(large_state))} 字符")
    
    # 测试不同序列化方式的性能
    methods = ['pickle', 'json', 'copy']
    results = {}
    
    for method in methods:
        if method == 'json':
            # JSON不能序列化复杂对象，使用简化版本
            test_state = {'data': list(range(1000)), 'text': "测试文本" * 100}
        else:
            test_state = large_state
        
        print(f"\n=== 测试 {method.upper()} 序列化 ===")
        
        # 序列化性能测试
        start_time = time.time()
        mementos = []
        
        for i in range(10):
            memento = SerializableMemento(test_state, method)
            mementos.append(memento)
        
        serialize_time = time.time() - start_time
        
        # 反序列化性能测试
        start_time = time.time()
        
        for memento in mementos:
            restored_state = memento.get_state()
        
        deserialize_time = time.time() - start_time
        
        # 计算平均大小
        avg_size = sum(m.get_size() for m in mementos) / len(mementos)
        
        results[method] = {
            'serialize_time': serialize_time,
            'deserialize_time': deserialize_time,
            'avg_size': avg_size
        }
        
        print(f"序列化时间: {serialize_time:.3f}秒")
        print(f"反序列化时间: {deserialize_time:.3f}秒")
        print(f"平均大小: {avg_size:.0f} bytes")
    
    # 性能对比总结
    print(f"\n=== 性能对比总结 ===")
    fastest_serialize = min(results.keys(), key=lambda k: results[k]['serialize_time'])
    fastest_deserialize = min(results.keys(), key=lambda k: results[k]['deserialize_time'])
    smallest_size = min(results.keys(), key=lambda k: results[k]['avg_size'])
    
    print(f"最快序列化: {fastest_serialize}")
    print(f"最快反序列化: {fastest_deserialize}")
    print(f"最小大小: {smallest_size}")


def demonstrate_java_comparison():
    """
    演示与Java的对比
    """
    print("\n=== Python vs Java 备忘录模式对比 ===")
    
    print("\n=== Java实现特点 ===")
    print("""
    Java备忘录模式的实现:
    
    // Java Memento类
    public class Memento {
        private final String state;
        private final long timestamp;
        
        public Memento(String state) {
            this.state = state;
            this.timestamp = System.currentTimeMillis();
        }
        
        public String getState() {
            return state;
        }
    }
    
    // Java Originator类
    public class Originator {
        private String state;
        
        public void setState(String state) {
            this.state = state;
        }
        
        public Memento createMemento() {
            return new Memento(state);
        }
        
        public void restoreFromMemento(Memento memento) {
            this.state = memento.getState();
        }
    }
    
    Java特点:
    - 严格的类型安全
    - 编译时检查
    - 需要实现Serializable接口进行序列化
    - 内存管理由JVM处理
    """)
    
    print("\n=== Python实现优势 ===")
    print("""
    Python备忘录模式的优势:
    
    1. 灵活的序列化:
       - 内置pickle模块
       - JSON序列化支持
       - 自定义序列化方式
       - 深拷贝机制
    
    2. 动态类型:
       - 无需预定义状态结构
       - 运行时类型检查
       - 支持任意对象类型
    
    3. 丰富的数据结构:
       - 字典、列表等内置类型
       - dataclass装饰器
       - 命名元组支持
    
    4. 内存管理:
       - 自动垃圾回收
       - 弱引用支持
       - 内存使用优化
    
    5. 并发支持:
       - 线程安全的实现
       - 异步操作支持
       - 锁机制
    """)
    
    print("\n=== 使用场景对比 ===")
    print("""
    Java适用场景:
    - 大型企业应用
    - 需要严格类型安全
    - 高性能要求
    - 复杂的对象图序列化
    
    Python适用场景:
    - 快速原型开发
    - 数据科学应用
    - 脚本和自动化
    - 需要灵活状态管理的应用
    """)


def main():
    """
    主函数 - 演示所有备忘录模式实现
    """
    print("Python备忘录模式完整演示")
    print("=" * 60)
    
    # 传统备忘录演示
    demonstrate_traditional_memento()
    
    # 增强型备忘录演示
    demonstrate_advanced_memento()
    
    # 文档编辑器演示
    demonstrate_document_editor()
    
    # 游戏状态管理器演示
    demonstrate_game_state_manager()
    
    # 性能对比演示
    demonstrate_performance_comparison()
    
    # Java对比演示
    demonstrate_java_comparison()
    
    print("\n=== 总结 ===")
    print("""
    备忘录模式的Python实现要点:
    
    1. 传统实现：严格遵循GoF模式，适合简单状态管理
    2. 增强实现：支持多种序列化方式，适合复杂状态
    3. 实际应用：文档编辑器、游戏存档等场景
    4. 性能优化：选择合适的序列化方式
    5. 线程安全：多线程环境下的状态管理
    
    选择建议:
    - 简单状态：使用传统实现
    - 复杂对象：使用pickle序列化
    - 跨平台：使用JSON序列化
    - 性能关键：使用深拷贝
    - 多线程：添加锁机制
    """)


if __name__ == "__main__":
    main()